import Taro from '@tarojs/taro'
import {setStorageSync, show, switchTab} from '@/utils/common'
import {login} from "@/api/auth";

/**
 * 登录
 */
export const taroLogin = (toRegister,toLogin) => {
  Taro.login({
    success: ({code}) => {
      login({ code }).then((re) => {
        const { openid,token } = re
        if (token) {
            setStorageSync('token', token)
			toLogin&&toLogin()
        }else if(openid){
			toRegister && toRegister(openid)
		}else {
          show('登录失败，请联系管理员')
        }
      })
    },
    fail: (err) => {
      if (err instanceof Error) {
         show('登录失败，请联系管理员' + err.message)
      }else{
         show('登录失败，请联系管理员')
      }
    }
  })
}


/**
 * 支付
 * @param data
 */
export function taroPay(data) {
  const { timeStamp, nonceStr, signType, paySign } = data
  return new Promise((resolve, reject) => {
    Taro.requestPayment({
      timeStamp,
      nonceStr,
      package: data.package,
      signType,
      paySign,
      success: (res) => resolve(res),
      fail: (err) => reject(err)
    })
  })
}

/**
 * 下载临时图片
 * @param filePath
 */
export function taroDownload(filePath) {
  return new Promise((resolve, reject) => {
    Taro.saveImageToPhotosAlbum({
      filePath,
      // @ts-ignore
      success: (res) => resolve(res),
      fail: (err) => reject(err)
    })
  })
}

/**
 * 下载图片到本地
 * @param url
 */
export function taroDownloadImage(url) {
  return new Promise((resolve, reject) => {
    Taro.downloadFile({
      url,
      success: (res) => {
        if (res.statusCode === 200) {
          const tempFilePaths = res.tempFilePath
          Taro.saveImageToPhotosAlbum({
            filePath: tempFilePaths,
            // @ts-ignore
            success: (r) => resolve(r),
            fail: (err) => reject(err)
          })
        }
      }
    })
  })
}

/**
 * 图片上传
 * @param data
 */
export function taroUploadFile(data) {
  const { url, filePath, fileName } = data
  return new Promise((resolve, reject) => {
    Taro.uploadFile({
      url,
      filePath,
      name: fileName,
      fileName: fileName,
      header: {
        'Content-Type': 'multipart/form-data'
      },
      success: (res) => resolve(res),
      fail: (err) => reject(err)
    })
  })
}

/**
 * 领卡
 * @param data
 */
export function taroAddCard(data) {
  const { card_id, api_ticket, timestamp, noncestr, sign } = data
  const cardExtData = {
    api_ticket,
    timestamp,
    nonce_str: noncestr,
    signature: sign
  }
  return new Promise((resolve, reject) => {
    Taro.addCard({
      cardList: [
        {
          cardId: card_id,
          cardExt: JSON.stringify(cardExtData)
        }
      ],
      // @ts-ignore
      success: (res) => resolve(res),
      fail: (err) => reject(err)
    })
  })
}

/**
 * 判断设备
 */
export function taroGetSystemInfo() {
  return new Promise((resolve, reject) => {
    Taro.getSystemInfo({
      success: (res) => resolve(res),
      fail: (err) => reject(err)
    })
  })
}

/**
 * 强制更新
 */
export function taroUpdate() {
  const updateManager = Taro.getUpdateManager()
  updateManager.onCheckForUpdate((res) => {
    if (!res.hasUpdate) return
    updateManager.onUpdateReady(() => {
      Taro.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success: (r) => {
          if (r.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
    updateManager.onUpdateFailed(() => {
      // 新的版本下载失败
      Taro.showModal({
        title: '已经有新版本了哟~',
        content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~'
      })
    })
  })
}

const NAVIGATOR_HEIGHT = 44
const TAB_BAR_HEIGHT = 50

/**
 * 返回屏幕可用高度
 * // NOTE 各端返回的 windowHeight 不一定是最终可用高度（例如可能没减去 statusBar 的高度），需二次计算
 * @param {*} showTabBar
 */
export function getWindowHeight(showTabBar = true) {
  const info = Taro.getSystemInfoSync()
  const { windowHeight, statusBarHeight, titleBarHeight } = info
  const tabBarHeight = showTabBar ? TAB_BAR_HEIGHT : 0

  if (process.env.TARO_ENV === 'rn') {
    return windowHeight - statusBarHeight - NAVIGATOR_HEIGHT - tabBarHeight
  }

  if (process.env.TARO_ENV === 'h5') {
    return `${windowHeight - tabBarHeight}px`
  }

  if (process.env.TARO_ENV === 'alipay') {
    // NOTE 支付宝比较迷，windowHeight 似乎是去掉了 tabBar 高度，但无 tab 页跟 tab 页返回高度是一样的
    return `${windowHeight - statusBarHeight - titleBarHeight + (showTabBar ? 0 : TAB_BAR_HEIGHT)}px`
  }

  return `${windowHeight}`
}
